from bson import ObjectId
from pymongo import MongoClient
from datetime import datetime


class MongoDatabase:
    def __init__(self):
        self.client = MongoClient("mongodb://localhost:27017/")  # 得到一个数据库连接
        self.db = self.client['test']  # 得到一个数据库对象

    def add_data(self, data):
        post = {
            "title": "cqc",
            "content": data,
            "created_at": datetime.now(),
        }
        return self.db.try_me.insert_one(post)  # 用insert_one方法插入数据post到try_me集合中

    def find_one(self):
        return self.db.try_me.find_one()

    def find_one_by_id(self, ID):
        return self.db.try_me.find_one({"_id": ObjectId(ID)})

    def find_one_by_name(self, name):
        return self.db.try_me.find_one({"title": name})

    def find_all(self):
        return self.db.try_me.find()

    def find_all_by_content(self, content):
        return self.db.try_me.find({"content": content})

    def update(self):
        return self.db.try_me.update_one({"content": "hello"}, {"$inc": {"x": 12}})

    def update_many(self):
        return self.db.try_me.update_many({"title": "new post"}, {"$inc": {"x": 12}})

    def delete(self):
        return self.db.try_me.delete_one({"title": "cqc"})

    def delete_many(self):
        return self.db.try_me.delete_many({"title": "cqc"})


a = MongoDatabase()
print(a.client.list_database_names())
db = a.client['test']


def main():
    obj = MongoDatabase()
    # rest = obj.add_data("hello")
    # print(rest.inserted_id)
    rest = obj.find_one()
    print(rest)
    rest = obj.find_one_by_id("67930835d05d54d7d0410540")
    print(rest)
    rest = obj.find_one_by_name("new post")
    print(rest)
    rest = obj.find_all()
    for i in rest:
        print(i)
    rest = obj.find_all_by_content("hello")
    for i in rest:
        print(i)
    rest = obj.update()
    print(rest)
    rest = obj.update_many()
    print(rest)
    rest = obj.delete()
    print(rest)
    print(rest.deleted_count)  # 打印删除的数量
    rest = obj.delete_many()
    print(rest)
    print(rest.deleted_count)  # 打印删除的数量
    print(db.try_me.count_documents({}))  # 统计try_me集合中的文档数量


if __name__ == '__main__':
    main()
